package com.poetry.vup.common.util.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.bouncycastle.util.encoders.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;

/**
 * JwtToken验证和读取的工具类，所有web服务公用
 * JWT token的格式：header.payload.signature
 */
@Component
public class JwtTokenUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);
//    private static final String CLAIM_KEY_USERNAME = "sub";
//    private static final String CLAIM_KEY_UID = "jti";
//    private static final String CLAIM_KEY_CREATED = "created";
    
    @Value("${jwt.pubkey}")
    private String pubkey;

    /**
     * 从token中获取JWT中的负载
     */
    public Claims getClaimsFromToken(String token) {
        X509EncodedKeySpec pubPKCS8 = new X509EncodedKeySpec(Base64.decode(pubkey));
        KeyFactory keyf;
        PublicKey pubKey = null;
		try {
			keyf = KeyFactory.getInstance("RSA");
			pubKey = keyf.generatePublic(pubPKCS8);
		} catch (NoSuchAlgorithmException e) {
			LOGGER.error("JWT生成公钥错误。");
			return null;
		} catch (InvalidKeySpecException e) {
			LOGGER.error("JWT公钥无效。");
			return null;
		}
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(pubKey)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            LOGGER.error("JWT格式验证失败:{}", token);
        }
        return claims;
    }
    
    /**
     * 从token中获取登录用户uid
     */
    public String getUserIDFromToken(String token) {
        String uid;
        try {
            Claims claims = getClaimsFromToken(token);
            uid = claims.getId();
        } catch (Exception e) {
        	uid = null;
        }
        return uid;
    }

    /**
     * 从token中获取登录用户名
     */
    public String getUserNameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    public String getUserToken(String token) {
        String uniqueIdentification;
        try {
            Claims claims = getClaimsFromToken(token);
            uniqueIdentification = (String) claims.get("ses");
        } catch (Exception e) {
            uniqueIdentification = null;
        }
        return uniqueIdentification;
    }

    /**
     * 验证token是否还有效
     *
     * @param token       客户端传入的token
     * @param userDetails 从数据库中查询出来的用户信息
     */
//    public boolean validateToken(String token, UserDetails userDetails) {
//        String username = getUserNameFromToken(token);
//        return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
//    }

    /**
     * 判断token是否已经失效
     */
    private boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return expiredDate.before(new Date());
    }

    /**
     * 从token中获取过期时间
     */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    /**
     * 判断token是否可以被刷新
     */
    public boolean canRefresh(String token) {
        return !isTokenExpired(token);
    }
}
